// https://leetcode.cn/problems/add-two-numbers/?envType=study-plan-v2&envId=top-interview-150

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* head = nullptr;
        ListNode* cur = head;
        int carray = 0;

        while (l1 || l2 || carray) {
            int num1 = l1 ? l1->val : 0;
            l1 = l1 ? l1->next : nullptr;
            int num2 = l2 ? l2->val : 0;
            l2 = l2 ? l2->next : nullptr;
            
            int sum = num1 + num2 + carray;
            carray = sum / 10;

            ListNode* node = new ListNode(sum % 10);
            if (!head) {
                head = node;
                cur = head;
            } else {
                cur->next = node;
                cur = cur->next;
            }
        }
        return head;
    }
};